import axios from 'axios'

// 创建Axios实例
const api = axios.create({
  baseURL: '/api/demo/',
  timeout: 10000
})

// 请求拦截器
api.interceptors.request.use(
  config => {
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// 响应拦截器
api.interceptors.response.use(
  response => {
    return response.data
  },
  error => {
    console.error('API请求错误:', error)
    return Promise.reject(error)
  }
)

// 用户认证API
export const login = async (username, pwd) => {
  return await api.post('/login', { username, pwd })
}

export const register = async (userData) => {
  return await api.post('/reg', userData)
}

// 分类相关API - 修改为使用现有可工作的方案
export const getAllCategories = async () => {
  try {
    const response = await api.get('/getallitems?typeIndex=1')
    // 改为过滤 completed=1 的数据作为分类
    const categories = Array.isArray(response) ? response.filter(item => item.completed === 1) : []
    console.log('获取的分类数据:', categories)
    return categories
  } catch (error) {
    console.error('获取分类列表失败:', error)
    return []
  }
}

export const addCategory = async (data) => {
  try {
    console.log('原始提交数据:', data)
    
    const categoryData = {
      title: String(data.title || '').trim(),
      body: String(data.body || '').trim(), 
      userid: Number(data.userid) || 1,
      completed: 1, // 改为1，表示分类（而不是999）
      categoryid: 0, // 改为0而不是null
      typeIndex: 1
    }
    
    // 验证必填字段
    if (!categoryData.title) {
      throw new Error('分类名称不能为空')
    }
    if (!categoryData.body) {
      throw new Error('分类描述不能为空') 
    }
    if (!categoryData.userid) {
      throw new Error('用户ID不能为空')
    }
    
    console.log('最终发送数据:', categoryData)
    
    const result = await api.post('/additem', categoryData)
    console.log('服务器返回结果:', result)
    
    return result
    
  } catch (error) {
    console.error('addCategory 详细错误:', error)
    throw error
  }
}

// 课程相关API
export const getCoursesByCategory = async (categoryId) => {
  try {
    const response = await api.get(`/getallitems?typeIndex=6&categoryid=${categoryId}`)
    return Array.isArray(response) ? response : []
  } catch (error) {
    console.error('获取课程列表失败:', error)
    return []
  }
}

export const getCourseById = async (courseId) => {
  return await api.get(`/getsingle?typeIndex=6&id=${courseId}`)
}

export const addCourse = async (data) => {
  try {
    console.log('原始课程数据:', data)
    
    // 时间戳转换为MySQL datetime格式
    const formatDateTime = (timestamp) => {
      if (!timestamp) return null
      const date = new Date(parseInt(timestamp))
      return date.toISOString().slice(0, 19).replace('T', ' ')
    }
    
    const courseData = {
      title: String(data.title || '').trim(),
      picPaths: String(data.picPaths || ''),
      userid: parseInt(data.userid) || 1,
      startTime: formatDateTime(data.startTime), // 转换为 'YYYY-MM-DD HH:MM:SS'
      body: String(data.body || '').trim(),
      endTime: formatDateTime(data.endTime),     // 转换为 'YYYY-MM-DD HH:MM:SS'
      categoryid: parseInt(data.categoryid) || 0,
      typeIndex: 6 // courses表
    }
    
    console.log('处理后的课程数据:', courseData)
    
    // 验证必填字段
    if (!courseData.title) {
      throw new Error('课程名称不能为空')
    }
    if (!courseData.body) {
      throw new Error('课程简介不能为空')
    }
    if (!courseData.userid) {
      throw new Error('用户ID不能为空')
    }
    
    const result = await api.post('/additem', courseData)
    console.log('服务器返回结果:', result)
    
    return result
    
  } catch (error) {
    console.error('addCourse 详细错误:', error)
    throw error
  }
}

// 任务相关API
export const getTasksByCourse = async (courseId) => {
  try {
    const response = await api.get(`/getallitems?typeIndex=7&parentid=${courseId}&parentType=课程`)
    return Array.isArray(response) ? response : []
  } catch (error) {
    console.error('获取任务列表失败:', error)
    return []
  }
}

export const addTask = async (data) => {
  const taskData = {
    ...data,
    typeIndex: 7,
    userid: parseInt(data.userid),
    parentid: parseInt(data.parentid),
    parentType: '课程'
  }
  return await api.post('/additem', taskData)
}

// 评论相关API
export const getCommentsByCourse = async (courseId) => {
  try {
    const response = await api.get(`/getallitems?typeIndex=4&articleid=${courseId}&replyType=课程`)
    return Array.isArray(response) ? response : []
  } catch (error) {
    console.error('获取评论列表失败:', error)
    return []
  }
}

export const addComment = async (data) => {
  try {
    console.log('原始评论数据:', data)
    
    // 验证必要字段
    if (!data.body || !data.body.trim()) {
      throw new Error('评论内容不能为空')
    }
    
    if (!data.userid) {
      throw new Error('用户ID不能为空')
    }
    
    if (!data.articleid) {
      throw new Error('课程ID不能为空')
    }
    
    const commentData = {
      body: String(data.body).trim(),
      userid: parseInt(data.userid),
      replyType: '课程',
      articleid: parseInt(data.articleid),
      typeIndex: 4 // comments表
    }
    
    // 再次验证转换后的数据
    if (isNaN(commentData.userid) || commentData.userid <= 0) {
      throw new Error('用户ID无效')
    }
    
    if (isNaN(commentData.articleid) || commentData.articleid <= 0) {
      throw new Error('课程ID无效')
    }
    
    console.log('处理后的评论数据:', commentData)
    
    const result = await api.post('/additem', commentData)
    console.log('服务器返回结果:', result)
    
    return result
    
  } catch (error) {
    console.error('addComment 详细错误:', error)
    throw error
  }
}